<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px"
        >
          <el-form-item label="课程名称" prop="userName">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入课程名称"
              clearable
              style="width: 180px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="教师姓名" prop="teacherId">
            <el-select filterable v-model="queryParams.teacherId" placeholder="请选择教师">
              <el-option v-for="(item,index) in teacherDictList" :key="index" :label="item.userName"
                         :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程类型" prop="typeId">
            <el-select filterable v-model="queryParams.typeId" placeholder="请选择课程类型">
              <el-option v-for="(item,index) in courseTypeDictList" :key="item.id" :label="item.name"
                         :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="售卖方法" prop="free">
            <el-select filterable v-model="queryParams.free" placeholder="请选择售卖方式">
              <el-option v-for="(item,index) in freeDictList" :key="index" :label="item.freeName"
                         :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select filterable v-model="queryParams.status" placeholder="请选择课程状态" style="width: 90%">
              <el-option v-for="(item,index) in statusDictList" :key="index" :label="item.status"
                         :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增
            </el-button>
          </el-col>

          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="courseList">
          <el-table-column label="课程名称" align="center" key="name" prop="name" v-if="columns[1].visible"
                           :show-overflow-tooltip="true"
          />
          <el-table-column label="教师名称" align="center" key="teacherName" prop="teacherName"
                           v-if="columns[2].visible"
                           :show-overflow-tooltip="true"
          />
          <el-table-column label="课程类型" align="center" key="typeName" prop="typeName" v-if="columns[3].visible"
                           :show-overflow-tooltip="true"
          />
          <el-table-column label="售卖方式" align="center" key="free" prop="free" v-if="columns[3].visible"
                           :show-overflow-tooltip="true"
          >

            <template slot-scope="scope">
              <span>{{ getFree(scope.row.free) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="课程状态" align="center" key="status" prop="status" v-if="columns[3].visible"
                           :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ getStatus(scope.row.status) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最新更新时间" align="center" prop="publishTime" v-if="columns[6].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.publishTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
              >修改
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          :total="page.total"
          :page.sync="page.current"
          :limit.sync="page.size"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入课程名称" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教师名称" prop="teacherId">
              <el-select filterable v-model="form.teacherId" placeholder="请选择教师">
                <el-option v-for="(item,index) in teacherDictList" :key="index" :label="item.userName"
                           :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程类型" prop="typeId">
              <el-select filterable v-model="form.typeId" placeholder="请选择课程类型">
                <el-option v-for="(item,index) in courseTypeDictList" :key="item.id" :label="item.name"
                           :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售卖方法" prop="free">
              <el-select filterable v-model="form.free" placeholder="请选择售卖方式" @change="isPriceShow">
                <el-option v-for="(item,index) in freeDictList" :key="index" :label="item.freeName"
                           :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select filterable v-model="form.status" placeholder="请选择课程状态">
                <el-option v-for="(item,index) in statusDictList" :key="index" :label="item.status"
                           :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="priceShow==0">
            <el-form-item label="价格(元)" prop="price">
              <el-input v-model="form.price" placeholder="请输入课程价格" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="4">
            <el-form-item label="上传封面" prop="coverUrl">
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-upload
              class="avatar-uploader"
              action="http://localhost/dev-api/xingyue/upload/img"
              :headers="upload.headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.coverUrl" :src="form.coverUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  visionTeacher,
  updateTeacher,
  deleteTeacher,
  teacherDict
} from '@/api/xingyue/teacher'
import { courseTypeDict } from '@/api/xingyue/courseType'
import { getCourseList, addCourse,getCourseById,updateCourse,deleteCourse } from '@/api/xingyue/course'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/ruoyi'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'User',
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 用户表格数据
      courseList: null,
      // 是否免费
      priceShow: 1,
      // 是否点击的是修改
      isUpdate:false,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,
      // 表单参数
      form: {},
      // 用户导入参数
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() }
      },
      // 查询参数
      queryParams: {
        // 课程名称
        name: undefined,
        typeId: undefined,
        teacherId: undefined,
        status: undefined
      },
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      // 教师字典集合
      teacherDictList: [],
      // 课程类型字典集合
      courseTypeDictList: [],
      freeDictList: [
        {
          id: 0,
          freeName: '付费'
        },
        {
          id: 1,
          freeName: '免费'
        }
      ],
      statusDictList: [
        {
          id: 1,
          status: '待上架'
        },
        {
          id: 2,
          status: '已上架'
        },
        {
          id: 3,
          status: '下架'
        },
        {
          id: 4,
          status: '已完结'
        }
      ],
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ]
    }
  },
  created() {
    this.getList()
    this.getTeacherDict()
    this.getCourseDict()
  },
  computed: {
    getFree() {
      return (free) => {
        if (free == 0) {
          return '收费'
        } else if (free == 1) {
          return '免费'
        } else {
          return '_'
        }
      }
    },
    getStatus() {
      return (status) => {
        if (status == 1) {
          return '待上架'
        } else if (status == 2) {
          return '已上架'
        } else if (status == 3) {
          return '下架'
        } else if (status == 4) {
          return '完结'
        } else {
          return '-'
        }
      }
    }
  },
  methods: {
    /** 图片上传*/
    handleAvatarSuccess(response) {
      if (response.code == 200) {
        this.$set(this.form, "coverUrl", response.data);
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },
    /** 图片上传之前的校验*/
    beforeAvatarUpload(file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    isPriceShow(e) {
      this.priceShow = e
    },

    /** 课程类型字典接口*/
    getCourseDict() {
      courseTypeDict().then(response => {
        if (response.code == 200) {
          this.courseTypeDictList = response.data
        } else {
          this.$message.error(response.msg || '服务器内部异常')
        }
      })
    },
    /** 教师字典接口 */
    getTeacherDict() {
      teacherDict().then(response => {
        if (response.code == 200) {
          this.teacherDictList = response.data
        } else {
          this.$message.error(response.msg || '服务器内部异常')
        }
      })
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      const data = {
        condition: this.queryParams,
        page: this.page
      }
      getCourseList(data).then(response => {
          this.courseList = response.data.list
          this.page.total = response.data.total
          this.loading = false
        }
      )
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.deptId = undefined
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加教师'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id
      getCourseById(id).then(response => {
        this.form = response.data
        this.form.id = id
        // 打开修改标志
        this.isUpdate = true
        if (response.data.price!=null) {
          this.priceShow = 0
        }
        this.open = true
        this.title = '修改课程信息'
      })
    },

    /** 提交按钮 */
    submitForm: function() {
      if (this.isUpdate==true) {
        updateCourse(this.form).then(response => {
          this.$modal.msgSuccess('修改成功')
          this.isUpdate=false
          this.open = false
          this.getList()
        })
      } else {
        addCourse(this.form).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除"' + row.name + '"的数据项？').then(function() {
        return deleteCourse(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    }

  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 5px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  padding-top: 80px;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
